/*
 *  Copyright 2010 dmakariev.
 * 
 */
package org.deltaset.faces.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author dmakariev
 */
final class StreamCurrentFile {

    private StreamCurrentFile() {
    }
    private static final Logger logger = Logger.getLogger(StreamCurrentFile.class.getName());

    static void streamCurrentFile(final CurrentFile currentFile) {


        try {
            final FacesContext facesContext = FacesContext.getCurrentInstance();
            final ExternalContext externalContext = facesContext.getExternalContext();
            final HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

            response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
//            response.setContentType("application/xml"); // Check http://www.w3schools.com/media/media_mimeref.asp for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
//            response.setHeader("Content-disposition", "attachment; filename=\"name.xml\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.


            if (null == currentFile) {
                facesContext.responseComplete();
                return;
            }

            if (currentFile.getContent().length < 1) {
                facesContext.responseComplete();
                return;
            }

            response.setContentType(currentFile.getContentType()); // Check http://www.w3schools.com/media/media_mimeref.asp for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
            response.setHeader("Content-disposition", "attachment; filename=\"" + currentFile.getName() + "\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.


            BufferedInputStream input = null;
            BufferedOutputStream output = null;

            try {
                final ByteArrayInputStream contentInputStream = new ByteArrayInputStream(currentFile.getContent());
                input = new BufferedInputStream(contentInputStream);
                output = new BufferedOutputStream(response.getOutputStream());

                byte[] buffer = new byte[1024];
                for (int length; (length = input.read(buffer)) > 0;) {
                    output.write(buffer, 0, length);
                }
            } finally {
                output.close();
                input.close();
            }

            facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
        } catch (IOException ioe) {
        } catch (IllegalStateException ex) {
            logger.log(Level.FINEST, ex.toString(), ex);
        }
    }
}
